using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Auto.Data.Security;
using BLL = Auto.Data.Systems.BLL;
using Auto.Data.Setting;
using Auto.Data.HumanResource;
using Auto.Components;

namespace BaseSystem._System
{
    public partial class UserEditor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
                InitDropDown();
            }
        }

        #region Init Page
        private void InitPage()
        {
            GVUsers.Attributes.Add("SortExpression", "UserID");
            GVUsers.Attributes.Add("SortDirection", " ASC");
            InitGridView();
        }
        #endregion Init Page

        #region Data Bind

        private void InitDropDown()
        {
            DataTable dt = new EmpBasic().GetDataByKey("", "");
            ddlEmpID.DataSource = dt;
            ddlEmpID.DataValueField = EmpBasic.FIELD_EmpID;
            ddlEmpID.DataTextField = EmpBasic.FIELD_Name;
            ddlEmpID.DataBind();
        }

        private void InitGridView()
        {
            DataTable dt = new Auto.Data.Security.Users().GetDataByKey(this.txtUserID.Text, this.ddlEmpID.SelectedValue, "");
            Session["UserEditor"] = dt;
            BindGridView();

        }
        private void BindGridView()
        {
            DataTable dt = (DataTable)Session["UserEditor"];
            if (dt != null)
            {
                string sortExpression = GVUsers.Attributes["SortExpression"];
                string sortDirection = GVUsers.Attributes["SortDirection"];
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dt.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                GVUsers.DataSource = dt;
                GVUsers.DataBind();
            }
        }

        private void BindChild(GridView gv)
        {
            if (Session["UserEditorGVChild"] == null)
            {
                EmpBasic emp = new EmpBasic();
                DataTable dt = emp.GetDataByKey("", "");
                Session["UserEditorGVChild"] = dt;
                gv.DataSource = dt;
            }
            else
            {
                gv.DataSource = (DataTable)Session["UserEditorGVChild"];
            }
            gv.Visible = true;
            gv.DataBind();
        }
        #endregion Data Bind

        #region Event

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            InitGridView();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (ViewState["add"] == null)
            {
                DataTable dt = (DataTable)Session["UserEditor"];
                Session["UserEditor"] = CreateColumn(dt);
                ViewState["add"] = "1";
                this.GVUsers.EditIndex = 0;
                BindGridView();
            }
        }


        protected void ddlEmpID_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitGridView();
        }

        #region GridView
        protected void GVUsers_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpress = e.SortExpression.ToString();
            string sortDirection = this.GVUsers.Attributes["SortDirection"].ToString();
            GVUsers.Attributes["SortExpression"] = sortExpress;
            GVUsers.Attributes["SortDirection"] = sortDirection == " DESC" ? " ASC" : " DESC";

            BindGridView();
        }


        protected void GVUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            bool resetBind = false;
            int id = Convert.ToInt32(this.GVUsers.DataKeys[e.RowIndex].Value);

            GridViewRow gvr = GVUsers.Rows[e.RowIndex];

            Label lbl = gvr.FindControl("lblDivID") as Label;
            string divID = lbl.Text;

            lbl = gvr.FindControl("lblEmpID") as Label;
            string empID = lbl.Text;



            TextBox txt = gvr.FindControl("txtUserID") as TextBox;
            string userID = txt.Text;

            txt = gvr.FindControl("txtUserName") as TextBox;
            string userName = txt.Text;

            txt = gvr.FindControl("txtPassword") as TextBox;
            string password = txt.Text;


            CheckBox chkPause = gvr.FindControl("chkPause") as CheckBox;
            bool pause = chkPause.Checked;

            Users users = new Users(userID);

            users.DivID = divID;
            users.EmpID = empID;
            users.UserName = userName;
            users.Pause = pause;
            users.Password = password == string.Empty ? users.Password : StrHelper.Encrypt(password);
            try
            {
                if (id == 0)
                {
                    resetBind = Add(users);
                }
                else
                {
                    resetBind = Update(users);
                }
            }
            catch (Exception ex)
            {
                Jscript.AjaxAlert(this, ex.Message);
            }
            if (resetBind)
            {
                ViewState["add"] = null;
                GVUsers.EditIndex = -1;
                InitGridView();
            }
        }

        protected void GVUsers_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GVUsers.EditIndex = e.NewEditIndex;
            BindGridView();
            int id = Convert.ToInt32(GVUsers.DataKeys[GVUsers.EditIndex].Value);
            if (id != 0)
            {
                TextBox txtUserID = GVUsers.Rows[GVUsers.EditIndex].FindControl("txtUserID") as TextBox;
                if (txtUserID != null)
                {
                    txtUserID.ReadOnly = true;
                }
                RequiredFieldValidator rvPassword = GVUsers.Rows[GVUsers.EditIndex].FindControl("rvPassword") as RequiredFieldValidator;
                if (txtUserID != null)
                {
                    rvPassword.Enabled = false;
                }
            }
        }

        protected void GVUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Import")
            {
                GridView gvChild = GVUsers.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("gvChild") as GridView;
                BindChild(gvChild);
            }
        }

        protected void GVUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            DeleteColumn();
            GVUsers.EditIndex = -1;
            BindGridView();
        }

        protected void GVUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GVUsers.PageIndex = e.NewPageIndex;
            BindGridView();
        }

        protected void gvChild_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView gv = (GridView)sender;
            gv.PageIndex = e.NewPageIndex;
            gv.DataBind();
            BindChild(gv);
        }

        protected void gvChild_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                GridViewRow gvr = GVUsers.Rows[this.GVUsers.EditIndex];

                GridView gv = (GridView)sender;
                GridViewRow gvChild = gv.Rows[Convert.ToInt32(e.CommandArgument)];

                Label lblEmpID = gvr.FindControl("lblEmpID") as Label;
                lblEmpID.Text = gvChild.Cells[1].Text;

                Label lblDivID = gvr.FindControl("lblDivID") as Label;
                lblDivID.Text = gvChild.Cells[2].Text;
                gv.Visible = false;
            }
        }
        #endregion GridView

        #endregion Event

        #region Operation

        private DataTable CreateColumn(DataTable result)
        {
            if (result != null)
            {
                DataRow dr = result.NewRow();
                dr[Users.FIELD_Pause] = false;
                dr[Users.FIELD_RecID] = 0;
                result.Rows.Add(dr);
            }
            return result;
        }

        /// <summary>
        /// Delete Column ID Value equal 0
        /// </summary>
        private void DeleteColumn()
        {
            if (ViewState["add"] != null)
            {
                DataTable result = (DataTable)Session["UserEditor"];

                if (result != null)
                {
                    foreach (DataRow dr in result.Rows)
                    {
                        if (dr[Users.FIELD_RecID].ToString() == "0")
                        {
                            result.Rows.Remove(dr);
                            Session["UserEditor"] = result;
                            break;
                        }
                    }
                } 
                ViewState["add"] = null;
            }
        }
        private bool Add(Users users)
        {
            bool result = false;
            if (users.IsNew)
            {
                if (users.Insert())
                {
                    result = true;
                }
                else
                {
                    Jscript.AjaxAlert(this, "insert failed ,please check it");
                }
            }
            else
            {
                Jscript.AjaxAlert(this, "The User ID is already exists,please check it");
            }
            return result;
        }
        private bool Update(Users users)
        {
            bool result = false;
            if (users.Update())
            {
                result = true;
            }
            else
            {
                Jscript.AjaxAlert(this, "update failed,please check it");
            }
            return result;
        }
        #endregion Operation
    }

}
